package com.example;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.BasicHttpContext;

import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class ClientMultiThreadedExecution {
    public static void main(String[] args) {

        final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(100);
        try (final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build()) {

            String[] urisToGet = {"http://hc.apache.org/",
                    "http://hc.apache.org/httpcomponents-core-ga/",
                    "http://hc.apache.org/httpcomponents-client-ga/"};
            GetThread[] threads = new GetThread[urisToGet.length];

            for (int i = 0; i < threads.length; i++) {
                final HttpGet httpGet = new HttpGet(urisToGet[i]);
                threads[i] = new GetThread(httpClient, httpGet, i + 1);
            }

            for (int i = 0; i < threads.length; i++) {
                threads[i].start();
            }

            for (int i = 0; i < threads.length; i++) {
                threads[i].join();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class GetThread extends Thread {

    private final CloseableHttpClient httpClient;
    private final HttpContext context;
    private final HttpGet httpget;
    private final int id;

    public GetThread(CloseableHttpClient httpClient, HttpGet httpget, int id) {
        this.httpClient = httpClient;
        this.context = new BasicHttpContext();
        this.httpget = httpget;
        this.id = id;
    }

    @Override
    public void run() {
        try(final CloseableHttpResponse response = httpClient.execute(httpget, context)){
            final HttpEntity entity = response.getEntity();
            System.out.println(EntityUtils.toString(entity));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}